var initScreen=function(callback){
    //$("html").css("font-size",document.documentElement.clientHeight/document.documentElement.clientWidth<1.5 ? (document.documentElement.clientHeight/603*312.5+"%") : (document.documentElement.clientWidth/375*312.5+"%")); //单屏全屏布局时使用,短屏下自动缩放
    $("html").css("font-size",document.documentElement.clientWidth/375*312.5+"%");
    if(callback)callback();
}

function _onorientationchange(e){
    if(window.orientation==90||window.orientation==-90){
    	//横版
        $("#forhorview").css("display", "-webkit-box");
        $("#wrap").hide();
    }else{
    	//竖屏
    	var st=setTimeout(initScreen,300);
        $("#forhorview").css("display", "none");
        $("#wrap").show();
    }
}
$(function(){
	initScreen();

    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize",function(e){
    	_onorientationchange(e);
    }, false);

    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) != 'micromessenger') {
    	$("body").addClass("fixed");
    }

    var	manifest = [
	    "data/girl1.js",
	    "data/girl2.js",
	    "data/girl3.js",
	    "data/girl4.js",
	    "data/girl5.js",
	    "data/girl6.js"
	];

	var manifest2 = [
		{src: "img/logo.png"},
	    {src: "img/logo-2.png"},
	    {src: "img/p-1-1.jpg"},
	    {src: "img/p-1-2.jpg"},
	    {src: "img/p-2-1.jpg"},
	    {src: "img/p-2-2.jpg"},
	    {src: "img/p-3-1.jpg"},
	    {src: "img/p-3-2.jpg"},
	    {src: "img/p-4-1.jpg"},
	    {src: "img/p-4-2.jpg"},
	    {src: "img/animate-1.png"},
	    {src: "img/animate-2.png"},
	    {src: "img/animate-3.png"},
	    {src: "img/animate-4.png"},
	    {src: "img/txt-1.png"},
	    {src: "img/txt-2.png"},
	    {src: "img/txt-3.png"},
	    {src: "img/txt-4.png"},
	    {src: "img/success.png"},
	    {src: "img/bg-success.jpg"},
	    {src: "img/layer.jpg"},
	    {src: "img/close.png"},
	    {src: "img/menu.png"},
	    {src: "img/menu-2.png"},
	    {src: "img/title.png"}
	]

	var loader = new createjs.LoadQueue(false);
	var loader2 = new createjs.LoadQueue(false);
    loader.loadManifest(manifest, true);
    loader.on("progress",onProgress);
    loader.on("complete", handleComplete);

    function onProgress(e){
    	var percent = Math.ceil(e.progress*100)+"%";
		$(".progress").text(percent);
    }

    //合并数组
	function merge() {
	    return Array.prototype.concat.apply([], arguments)
	}

	var girl,girlAnim;

    function handleComplete(){
    	girl = merge(girl1,girl2,girl3,girl4,girl5,girl6);

    	girlAnim = frameAnimation.anims($('#gril'),girl,2,1,function(){
			$(".shake-box").addClass("show");
    		//canShake = true;
		});

    	$("#loading").hide();
    	$("#index").addClass("fadeIn");
    	girlAnim.start();
    	loader2.loadManifest(manifest2, true);
    }

    var canShake = false;
    var type = 1;
    var prevRandom;

    var randomFn = function(){
    	var random = Math.round(Math.random()*3+1);
    	if(random==prevRandom){
    		randomFn();
    	}else{
    		prevRandom = random;
    		type = random;
    	}
    }
    Shake.init({
        threshold:1000,
        callback:function(times){
        	if(canShake){
        		canShake = false;
        		//var random = Math.round(Math.random()*3+1);
        		randomFn();
        		$("#index").addClass("fadeOut");
        		//$("#reward").show();
        		$("#reward").attr("class","reward-"+type+" fadeIn");
        		$("#result").attr("class","result-"+type);
        		/*var form = '<div class="formset" id="formset">'+
								'<span class="item">'+
									'<label for="name">姓名：</label>'+
									'<input type="text" id="name"/>'+
								'</span>'+
								'<span class="item">'+
									'<label for="tel">手机：</label>'+
									'<input type="tel" id="tel" maxlength="11"/>'+
								'</span>'+
							'</div>';
        		$("#result").append(form);*/
        		$("#result").append('<iframe src="iframe.html" id="formFrame" name="formFrame"></iframe>');
        		setTimeout(function(){
        			$("#reward").addClass("fadeOut");
        			$("#result").show().addClass("fadeIn");
        		},2500)
        		stm_clicki('send', 'event', 'shake');
        	}
        }
    });

    $(".menu").click(function(){
      	$(this).parent().toggleClass("show");
    });

    $(".rule").click(function(){
    	$("#rule-box").show();
		setTimeout(function(){
			$("#rule-box").addClass("show");
		},100);
		stm_clicki('send', 'event', 'more');
   	});
   	
   	$(".publish").click(function(){
    	$("#win-box").show();
		setTimeout(function(){
			$("#win-box").addClass("show");
		},100);
		//stm_clicki('send', 'event', 'more');
   	});

   	$(".close").click(function(){
   		var pop = $(this).parents(".pop");
   		pop.removeClass("show");
		setTimeout(function(){
			pop.hide();
		},300);
   	});

    $(".subForm").click(function(){
    	//var name = $.trim($("#name").val());
		//var phone = $.trim($("#tel").val());
		var name = window.frames["formFrame"].document.getElementById("name").value;
		var phone = window.frames["formFrame"].document.getElementById("tel").value;
		if(name==""){
			layer.open({
				content: "请填写姓名",
				shadeClose: false,
				time: 1,
				className: "layer-alert"
			})
			return;
		}
		if(phone==""){
			layer.open({
				content: "请填写手机号码",
				shadeClose: false,
				time: 1,
				className: "layer-alert"
			})
			return;
		}
		if (!/^1[34578]\d{9}/.test(phone)) {
			layer.open({
				content: "请输入正确的电话号码",
				shadeClose: false,
				time: 1,
				className: "layer-alert"
			})
			return;
		}
		$.ajax({
			type:"get",
			url:"http://holiday2017.esteelauderclub.cn/api.php?action=submit",
			dataType: "jsonp",
			data: {
				name: name,
				phone: phone,
				type: type
			},
			success: function(res){
				if(res.status=="true"){
					$("#result").addClass("fadeOut")
					$("#success").addClass("fadeIn");
					$("#formFrame").remove();
				}else{
					layer.open({
						content: res.msg,
						shadeClose: false,
						time: 1,
						className: "layer-alert"
					})
				}
			}
		});

		stm_clicki('send', 'event', 'Apply', {
		 customActionId: 1,
		 customActionLabel1:name ,
		 customActionLabel2:phone,
		 customActionLabel3:type
		});
   });

   $(".share").click(function(){
		$(".share-box").show();
		setTimeout(function(){
			$(".share-box").addClass("show");
		},100);
		stm_clicki('send', 'event', 'share');
	});

	$(".share-box").click(function(){
		$(this).removeClass("show");
		setTimeout(function(){
			$(".share-box").hide();
		},300);
	});

	$(".try").click(function(){
		$("#success").removeClass("fadeIn");
		$("#reward").removeAttr("class");
		$("#result").removeAttr("class");
		$("#index").attr("class","fadeIn");
		canShake = true;
		//$(".formset").remove();
		var el = document.getElementById("formset");
		delete el.parentNode.removeChild(el);
		stm_clicki('send', 'event', 'retry');
	});

	$(".back-btn").click(function(){
		$("#success").removeClass("fadeIn");
		$("#reward").removeAttr("class");
		$("#result").removeAttr("class");
		$("#index").attr("class","fadeIn");
		canShake = true;
		//$(".formset").remove();
		var el = document.getElementById("formset");
		delete el.parentNode.removeChild(el);
		stm_clicki('send', 'event', 'back');
	});

	var src = window.location.href;

	$.getJSON('http://member.esteelauderclub.cn/api/service/jssignature/38?accesstoken=564E4464-7817-402D-9FD9-8B7A176B38C1&url='+encodeURIComponent(location.href.split('#')[0]) + '&callback=?', function(data) {
		var wxConfig = data.datas;
		wxConfig.debug = false;
		wxConfig.jsApiList = ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'];
		wx.config(wxConfig);

		wx.ready(function(){
			console.log("success")
			var shareMeta = {
				title: '雅诗兰黛成全你的美丽礼享',
			    desc: '年度礼享嘉年华，精彩不容错过。',
			    link: src,
			    imgUrl: 'http://holiday2017.esteelauderclub.cn/img/share-1.jpg'
			}
			var shareMetaTimeline = {
				title: '我想要的美丽礼享统统在这里！',
				link: src,
				imgUrl: 'http://holiday2017.esteelauderclub.cn/img/share-2.jpg'
			}
			//分享到朋友圈
			wx.onMenuShareTimeline($.extend(shareMetaTimeline,{
				success: function () {
					stm_clicki('send', 'event', '分享到朋友圈');
			    }
			}));

			//分享给朋友
			wx.onMenuShareAppMessage($.extend(shareMeta,{
				success: function () {
					stm_clicki('send', 'event', '分享给好友');
			    }
			}));
		});
	})
	
	var isSwiper = false;
	var isIndexPage = true;
	$(".product").click(function(){
		isIndexPage = $(this).hasClass("index")
		stm_clicki('send', 'event', 'booklet');
		canShake = false;
		$("#product-box").show();
		if(!isSwiper){
			var mySwiper = new Swiper ('.swiper-container', {
				loop: true,
				onSlideChangeStart: function(swiper){
					var index = swiper.activeIndex;
					if(index==3){
						$(".back").addClass("grey");
					}else{
						$(".back").removeClass("grey");
					}
				}
			})
		}
		setTimeout(function(){
			$("#product-box").addClass("show");
		},100);
	})
	
	$(".guide").click(function(){
		$(this).hide();
	})
	
	$(".back").click(function(){
		$("#product-box").removeClass("show");
		setTimeout(function(){
			$("#product-box").hide();
		},300)
		//$("#index").attr("class","fadeIn");
		//$("#success").removeAttr("class");
		if(isIndexPage){
			canShake = true;
		}
	})
})
